﻿using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Controls;

namespace VNet.VisiSuite.Controls
{

    public interface IErrorViewer
    {
        void SetElement(DependencyObject element);
    }
    /// <summary>
    /// Interaction logic for ValidationSummary.xaml
    /// </summary>
    public partial class ValidationSummary : UserControl, IErrorViewer
    {
        private List<DependencyObject> _elements = new List<DependencyObject>();
        private ObservableCollection<string> _errorMessages = new ObservableCollection<string>();
        private Dictionary<string, List<ValidationError>> _invalidList = new Dictionary<string, List<ValidationError>>();

        public ValidationSummary()
        {
            InitializeComponent();
            this.Loaded += ErrorViewer_Loaded;
        }

        void ErrorViewer_Loaded(object sender, RoutedEventArgs e)
        {
            _itemsControl.ItemsSource = _errorMessages;
        }

        private void Element_ValidationError(object sender, ValidationErrorEventArgs e)
        {
            var errorContent = e.Error.ErrorContent.ToString();
            if (e.Action == ValidationErrorEventAction.Added)
            {
                if (_invalidList.ContainsKey(errorContent))
                    _invalidList[errorContent].Add(e.Error);
                else
                    _invalidList.Add(errorContent, new List<ValidationError>() { e.Error });
            }
            else if (e.Action == ValidationErrorEventAction.Removed)
            {
                if (_invalidList.ContainsKey(errorContent) && _invalidList[errorContent].Contains(e.Error))
                    _invalidList[errorContent].Remove(e.Error);
                if (_invalidList.ContainsKey(errorContent) && _invalidList[errorContent].Count == 0)
                    _invalidList.Remove(errorContent);
            }

            _errorMessages.Clear();
            foreach (var key in _invalidList.Keys)
            {
                _errorMessages.Add(key);
            }
        }

        #region IErrorViewer Members

        public void SetElement(DependencyObject element)
        {
            if (!_elements.Contains(element))
                _elements.Add(element);
            Validation.AddErrorHandler(element, Element_ValidationError);
        }

        #endregion
    }
}
